package comlookupd

import (
	"gitee.com/liukexing/mqbroker/core/driver/component"
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"time"
)

func NewCommandHandle() *pubsub.CommandServerHandle {
	return &pubsub.CommandServerHandle{
		Command: map[string]typedef.CommonMsgConfig{
			"Find": typedef.CommonMsgConfig{
				Handle: FindCmd,
				Sub:    typedef.CommonMsgCheck{Receiver: Config.Info.Module},
			},
			"Register":{
				Handle: RegisterCmd,
				Sub:    typedef.CommonMsgCheck{Receiver: Config.Info.ID},
			},
			"UpConfig":{
				Handle: UpConfigCmd,
				Sub:    typedef.CommonMsgCheck{Receiver: Config.Info.ID},
			},
			"Health": typedef.CommonMsgConfig{
				Handle: HealthCmd,
				Sub:    typedef.CommonMsgCheck{Receiver: Config.Info.ID},
			},
		},
	}
}

func EmptyCmd(Args map[string]interface{}) (map[string]interface{}, error) {
	return  nil,nil
}
//查找
func FindCmd(Args map[string]interface{}) (map[string]interface{}, error) {
	return map[string]interface{}{
		"info": Config.Info,
	}, nil
}
//注册
func RegisterCmd(Args map[string]interface{}) (map[string]interface{}, error) {
	cmd := struct {
		Info typedef.ModuleInfo
	}{}
	typedef.Decode(Args,&cmd)
	info := cmd.Info
	ComMap.Store(info.ID,typedef.ComInfo{
		Info:info,
		LastUpdate:time.Now(),
	})
	return  nil,nil
}
//配置上传
func UpConfigCmd(Args map[string]interface{}) (map[string]interface{}, error) {
	cmd := struct {
		Component string
		Msgflow string
		Config map[string]interface{}
	}{}
	if err := typedef.Decode(Args,&cmd);err !=nil{
		return nil,err
	}
	cmd.Config["LastUpdate"] = time.Now()
	if v, ok := ConfigMap.Load(cmd.Component); ok {
		v.(map[string]interface{})[cmd.Msgflow] = cmd.Config
		ConfigMap.Store(cmd.Component,v)
	} else {
		ConfigMap.Store(cmd.Component,map[string]interface{}{cmd.Msgflow:cmd.Config})
	}
	return  nil,nil
}
//健康检查
func HealthCmd(Args map[string]interface{}) (map[string]interface{}, error) {
	LastTick = time.Now()
	return component.HealthCmd(Config.Info)
}
